import React, {PropsWithChildren, useEffect, useState} from 'react'
import {observer} from "mobx-react";
import {useLoad} from "@tarojs/taro";
import {goodsPageStackStore} from "../store/GoodsPageStackStore";
import {getGoodsDetail, updateGoods} from "../apis/GoodsApi";
import Scaffold from "../components/Scaffold";
import GoodsEditForm from "../components/GoodsEditForm";

export interface GoodsEditProps extends PropsWithChildren {

}

const GoodsEdit: React.FC<GoodsEditProps> = ({}) => {
    const [id, setId] = useState<number>()
    useLoad(params => {
        setId(Number(params.id))
    })
    let detail = goodsPageStackStore.detail;
    useEffect(() => {
        if (id && !detail) {
            getGoodsDetail(id).then(response => {
                goodsPageStackStore.setDetail(response.data)
            })
        }
    }, [id, detail]);
    return <>
        <Scaffold title={"编辑货品"}>
            {!!detail && !!id &&<GoodsEditForm initialValue={detail ? {
                ...detail,
                units:detail.units,
                brandId:detail.brand?.id,
                categoryId:detail.category?.id,

            } : undefined} onConfirm={async (value, _) => {
                await updateGoods(id,{
                    ...value,
                    subGoodsList: detail?.subGoodsList??[],
                })
                let response = await getGoodsDetail(id);
                goodsPageStackStore.updateDetail(response.data)
            }}/>}
        </Scaffold>
    </>
}

export default observer(GoodsEdit)


